package com.lfy.modules.safety.limit;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
/**
 *  限流实例
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/4/25 0:56
 */
@Slf4j
public class Limit {
    private final ConcurrentHashMap<Long, Integer> limitMap = new ConcurrentHashMap<>();

    public  void setCount() {
        limitMap.put(System.currentTimeMillis(), 1);
    }

    public  int getCount(long startTime) {
        int count = 0;
        Iterator<Map.Entry<Long, Integer>> iterator = limitMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, Integer> entry = iterator.next();
            // 删除无效过期的子窗口计数器
            if (entry.getKey() < startTime) {
                iterator.remove();
            } else {
                //累加当前窗口的所有计数器之和
                count = count + entry.getValue();
            }
        }
        return count;
    }
}